package com.ctn.bootstarp.tags;

import java.util.Locale;
import java.util.Properties;

import javax.servlet.jsp.PageContext;

import org.springframework.context.MessageSource;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

import tldgen.Tag;

import com.ctn.bootstarp.tags.util.TagUtil;

/**
 * @author weiqi
 * @date 2013年8月6日
 */
@Tag
public class SpringHolderTag extends RequestContextAwareTag {
	
	private static final long serialVersionUID = -7952199043575355631L;
	private static ThreadLocal<Locale> localeLocal = new ThreadLocal<Locale>();
	private static MessageSource messageSource;
	private static ThreadLocal<PageContext> pageContextLocal = new ThreadLocal<PageContext>();
	
	public static String getSpringMessage(String code,String text,Object[] args){
		if(null==messageSource){
			return TagUtil.printError("页面没有初始化<bsutil:SpringHolderTag/>标签，无法使用国际化函数! "+code);
		}
		PageContext pageContext = pageContextLocal.get();
		if(null!=pageContext){
			Properties fields = (Properties) pageContext.getAttribute("fields",pageContext.getAttributesScope("fields"));
			if(fields.containsKey(code)) {
				return fields.getProperty(code);
			}
		}
		return messageSource.getMessage(code, args, text, localeLocal.get());
	}
	

	@Override
	protected int doStartTagInternal() throws Exception {
		localeLocal.set(this.getRequestContext().getLocale());
		if(null == messageSource) {
			messageSource = this.getRequestContext().getMessageSource();
		}
		int scope = pageContext.getAttributesScope("fields");
		if(scope>0&&scope<5){
			pageContextLocal.set(pageContext);
			/*Object fields = pageContext.getAttribute("fields",scope);
			if(null!=fields) {
				modulesFieldsLocal.set((Properties) fields);
			}*/
		}
		return SKIP_BODY;
	}


}
